from  rest_framework import serializers
from goods.models import SKUImage, SKU

from fdfs_client.client import Fdfs_client
from django.conf import settings
from celery_tasks.static_html.tasks import get_detail_html

class SKUImageSerializer(serializers.ModelSerializer):
    """
    商品图片序列化器
    """
    sku=serializers.PrimaryKeyRelatedField(read_only=True)
    class Meta:
        model = SKUImage
        fields=('id','sku','image')

    # 重写create方法，将图片上传到fastDFS中
    def create(self, validated_data):
        # 1.建立fastDFS连接对象
        client=Fdfs_client(settings.FASTDFS_PATH)
        # 2.获取图片数据
        request=self.context['request']
        image_file=request.data.get('image')
        # 3.上传图片
        res=client.upload_by_buffer(image_file.read())
        # 4.判断返回结果
        if res['Status']!='Upload successed':
            raise serializers.ValidationError('图片上传失败')
        # 5.上传成功将返回的文件路径保存到图片表中
        image_url=res['Remote file_id']
        img=SKUImage.objects.create(image=image_url,sku_id=request.data['sku'])
        # 6.详情页静态化处理
        sku=SKU.objects.get(sku_id=request.data['sku'])
        if not sku.default_image:
            # 没有默认图片
            sku.default_image=image_url
            sku.save()
            # 异步生成静态化页面
        get_detail_html.delay(request.data['sku'])

        # 7.返回保存后的图片对象数据
        return img


    # 重写update方法，将图片上传到fastDFS中
    def update(self, instance, validated_data):
        # 1.建立fastDFS连接对象
        client=Fdfs_client(settings.FASTDFS_PATH)
        # 2.获取图片数据
        request=self.context['request']
        image_file=request.data.get('image')
        # 3.上传图片
        # res=client.upload_by_buffer(image_file.read())
        res=client.upload_by_buffer(image_file.read())
        # 4.判断返回结果
        if res['Status']!='Upload successed':
            raise serializers.ValidationError('图片上传失败')
        # 5.上传成功将返回的文件路径更新到图片表中
        image_url=res['Remote file_id']
        instance.image=image_url
        instance.save()
        # 6.详情页静态化处理
        sku = SKU.objects.get(sku_id=request.data['sku'])
        if not sku.default_image:
            # 没有默认图片
            sku.default_image = image_url
            sku.save()
            # 异步生成静态化页面
        get_detail_html.delay(request.data['sku'])

        # 7. 返回更新后的图片对象数据

        return instance



class SKUSerializer(serializers.ModelSerializer):
    """SKU商品序列化器"""
    class Meta:
        model=SKU
        fields={'id','name'}